package com.Mobile.Action;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.springframework.beans.factory.annotation.Autowired;
import com.Entity.Users;
import com.Service.UsersService;

public class UpdatePasswordAction implements ServletResponseAware {
//更换密码
	private HttpServletResponse response;//response闁诲海鏁搁、濠囨寘?
	private int flag=0;
	@Autowired
	private UsersService usersservice;
	private Users user=new Users();
	public UsersService getUsersservice() {
		return usersservice;
	}

	public void setUsersservice(UsersService usersservice) {
		this.usersservice = usersservice;
	}
	
	public void updatepassword() throws ServletException,IOException {
		
		String username=ServletActionContext.getRequest().getParameter("UserName");
		String newpassword=ServletActionContext.getRequest().getParameter("newPassword");
		String oldpassword=ServletActionContext.getRequest().getParameter("oldPassword");
		
		username = java.net.URLDecoder.decode(username,"UTF-8");
		newpassword = java.net.URLDecoder.decode(newpassword,"UTF-8");
		oldpassword = java.net.URLDecoder.decode(oldpassword,"UTF-8");
		
		JSONObject returnjson=new JSONObject();
		
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json;charset=utf-8"); 
		
		try {
			PrintWriter out = response.getWriter();
			List<Users> userlist = this.usersservice.CheckLogin(username,oldpassword);
			System.out.println(userlist.isEmpty());
			if(userlist!=null&&!userlist.isEmpty()){
				flag=1;								
				user=userlist.get(0);				
				String password=user.getPassword();
				System.out.println("password:"+password);
				returnjson.put("flag",flag);
				user.setPassword(newpassword);
				this.usersservice.save(user);
			}
			else{
				flag=0;
				returnjson.put("flag", flag);
			}						
			out.println(returnjson.toString());
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response=response;		
	}

	public Users getUser() {
		return user;
	}

	public void setUser(Users user) {
		this.user = user;
	}

}
